#include "UpdateIcons.h"
#include "GetSettings.h"
#include "Error.h"
#include "Switcher.h"

vector<string> UpdatePopup() {
    WIN32_FIND_DATA FileInfo;
    HANDLE FileFindHandle;
    HANDLE ExeFileFindHandle;
    vector<string> AllPortableApps;
    string PortableAppsDir = GetValue("PortableAppsDir");
    string FileName;
    string DirName;
    string DirPath;
    //string Tree = "Installed Apps:\n";
    string Popup = 
        "; **************************\n"
        "; * DO NOT EDIT THIS FILE  *\n"
        "; *(any edits will be lost)*\n"
        "; **************************\n"
        "; This is an automaticly generated file with all the\n"
        "; PortableApps that were installed at the last refresh\n"
        "; (or run of the shellswitcher). All edits will be lost\n"
        "; the next time you run LiteStepPortable.\n";
    string LSXAlias = Popup;
    bool FindNextFileSuccess = true;
    bool FindNextDirSuccess = true;
    
    //Info(PortableAppsDir);
    FileFindHandle = FindFirstFile(
        (PortableAppsDir.substr(0,
            PortableAppsDir.length()-1)).c_str(),
        &FileInfo);
    if (FileFindHandle != INVALID_HANDLE_VALUE) {
        PortableAppsDir += "*";
        FindClose(FileFindHandle);
        FileFindHandle = FindFirstFile(
            PortableAppsDir.c_str(),
            &FileInfo);
        PortableAppsDir = PortableAppsDir.substr(0, PortableAppsDir.length()-1);
        //Info(PortableAppsDir);
        if (FileFindHandle != INVALID_HANDLE_VALUE) {
            while (FindNextDirSuccess) {
                //Info(string(FileInfo.cFileName));
                DirName = FileInfo.cFileName;
                if (((FileInfo.dwFileAttributes &
                    FILE_ATTRIBUTE_DIRECTORY) ==
                    FILE_ATTRIBUTE_DIRECTORY) &&
                    (DirName != ".") &&
                    (DirName != "..")) {
                        DirName = PortableAppsDir;
                        DirName += FileInfo.cFileName;
                        DirPath = DirName;
                        DirName += "\\*";
                        //Info("Dir: " + DirName);
                        ExeFileFindHandle = FindFirstFile(
                            DirName.c_str(),
                            &FileInfo);
                        if (ExeFileFindHandle != INVALID_HANDLE_VALUE) {
                            while (FindNextFileSuccess) {
                                //Info("File: " + DirName + " " + string(FileInfo.cFileName));
                                if ((FileInfo.dwFileAttributes &
                                    FILE_ATTRIBUTE_DIRECTORY) !=
                                    FILE_ATTRIBUTE_DIRECTORY) {
                                        FileName = FileInfo.cFileName;
                                        //Info("Def File: " + FileName);
                                        int ExtIndex = FileName.rfind(".");
                                        if (ExtIndex > 0) {
                                            if (FileName.substr(
                                                ExtIndex, FileName.length())
                                                == ".exe") {
                                                    // Add the current app to the popup list
                                                    Popup += "*Popup \"";
                                                    Popup += FileName.substr(0, ExtIndex);
                                                    Popup += "\" \"";
                                                    Popup += DirPath;
                                                    Popup += "\\";
                                                    Popup += FileName;
                                                    Popup += "\"\n";
                                                    // And to the lsxcommand alias file...
                                                    // Converts to lowercase
                                                    string LowerFileName;
                                                   	for (size_t i = 0; i <= FileName.length(); i++) {
		                                                LowerFileName += tolower(FileName[i]);
                                                    }
                                                    int PortableIndex = LowerFileName.rfind("portable");
                                                    if (PortableIndex < 1)
                                                        PortableIndex = ExtIndex;
                                                    LSXAlias += "*CommandAlias \"";
                                                    LSXAlias += FileName.substr(0, PortableIndex);
                                                    LSXAlias += "\" \"";
                                                    LSXAlias += DirPath;
                                                    LSXAlias += "\\";
                                                    LSXAlias += FileName;
                                                    LSXAlias += "\"\n";
                                                    // Add The portableapp to the list, for adding desktop
                                                    // shortcuts (after litestep loads)
                                                    AllPortableApps.push_back(DirPath + "\\" + FileName);
                                                    //Info("Portableapp found!\n" + FileName);
                                            } else {
                                                //Info("extension is: " +
                                                //    FileName.substr(
                                                //        ExtIndex, FileName.length()));
                                            }
                                        }
                                }
                            FindNextFileSuccess = FindNextFile(
                                ExeFileFindHandle,
                                &FileInfo);
                            }
                        FindNextFileSuccess = true;
                        }
                }
                FindNextDirSuccess = FindNextFile(
                    FileFindHandle,
                    &FileInfo);
            }
            FindClose(FileFindHandle);
            FindClose(ExeFileFindHandle);
        }
        //Info(Tree);
        //Info(Popup);
            //if (MessageBox(NULL, Popup.c_str(), "Write to disk?", MB_YESNO) == IDYES) {
                 ofstream PopupWriter;
                 // Open the file for writing
                 PopupWriter.open(GetValue("PortableApps popup file").c_str());
                 // If it was successfull...
                 if (PopupWriter.is_open()) {
                     // Write to the file...
                     PopupWriter << Popup;
                 } else {
                     // There was an error :(
                     Warning("There was an error writing to PortableApps.rc.\n"
                         "your list may not have the most recent apps.\n"
                         "A likely cause of this is that the path is invalid.\n"
                         "Please check settings.ini!");
                     //system("PAUSE");
                     //exit( EXIT_FAILURE );
                 }
                 PopupWriter.close();
                 ofstream LSXWriter;
                 // Open the file for writing
                 LSXWriter.open(GetValue("PortableApps LSX file").c_str());
                 // If it was successfull...
                 if (LSXWriter.is_open()) {
                     // Write to the file...
                     LSXWriter << LSXAlias;
                 } else {
                     // There was an error :(
                     Warning("There was an error writing to PortableApps.rc.\n"
                         "your list may not have the most recent apps.\n"
                         "A likely cause of this is that the path is invalid.\n"
                         "Please check settings.ini!");
                     //system("PAUSE");
                     //exit( EXIT_FAILURE );
                 }
                 LSXWriter.close();
            //}
            //PromptAction();
            //AddAllShortcuts(AllPortableApps);
            //Info(LSXAlias);
    } else {
        Error("Portableapps diretory is not valid!\n"
            "check settings.ini to change the path");
    }
    return AllPortableApps;
}

void UpdateIcons(const vector<string>& AllPortableApps) {
    string Name;
    string Path;
    //Info("TEST 4.1");
    string DesktopFolderPath = GetValue("DesktopFolderPath");
    bool CreateDesktopShortcuts = GetBoolValue("CreateDesktopShortcuts");
    if (CreateDesktopShortcuts) {
        //Info("TEST 4.2");
        for (int i=0; i < AllPortableApps.size(); i++) {
            //Info("TEST 4.2.1");
            Path = AllPortableApps[i];
            //Info("TEST 4.2.1.1");
            int SlashLoc = Path.rfind("\\")+1;
            int ExtLoc = Path.rfind(".")-SlashLoc;
            //Path.rfind(".exe");
            /*ostringstream testing;
            testing << Path;
            testing << "\n";
            testing << SlashLoc;
            testing << "\n";
            testing << ExtLoc;
            Info(testing.str());*/
            //Info("TEST 4.2.2");
            if ((SlashLoc > 0) && (ExtLoc > 0)) {
                Name = Path.substr(
                    SlashLoc,
                    ExtLoc);
                //Info("IN 1");
            } else if (SlashLoc < 1) {
                Error(Path + 
                    "\nIs not a valid path.");
            } else if (ExtLoc < 1) {
                Name = Path.substr(
                    SlashLoc,
                    Path.length());
            } else {
                Error("Something whent really, really, wrong.\n"
                   "This should NEVER, EVER, happen.");
                exit( EXIT_FAILURE );
            }
            //Info(Path + "\n" + Name);
            //Info(Path + "\n" + Name);
            /*SHFILEINFO FileInfo;
            SHGetFileInfo(
                Path.c_str(),
                0,
                &FileInfo,
                sizeof(FileInfo),
                SHGFI_ATTRIBUTES);*/
            
            /*RestartDialog(
                NULL,
                "WHAT",
                EWX_LOGOFF);*/
            //Info("TEST 4.3");
            CreateLink(
                Path.c_str(),
                (DesktopFolderPath +
                    Name + ".lnk").c_str(),
                    "Need to add this :P"); 
        }
    }
}

HRESULT CreateLink(LPCSTR lpszPathObj, LPCSTR lpszPathLink, LPCSTR lpszDesc)
{
    HRESULT hres;
    IShellLink *psl ;
    CoInitialize (NULL);


    // Get a pointer to the IShellLink interface.
    hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
                            IID_IShellLink, (LPVOID*)&psl);
    if (SUCCEEDED(hres))
    {
        IPersistFile* ppf;
 
        // Set the path to the shortcut target and add the description.
        hres = psl->SetPath(lpszPathObj);
        hres = psl->SetDescription(lpszDesc);

        // Query IShellLink for the IPersistFile interface for saving the
        // shortcut in persistent storage.

        hres = psl->QueryInterface(IID_IPersistFile, (LPVOID*)&ppf);  

        if (SUCCEEDED(hres))
        {
            WCHAR wsz[MAX_PATH];
 
            // Ensure that the string is Unicode.
           hres =  MultiByteToWideChar(CP_ACP, 0, lpszPathLink, -1, wsz, MAX_PATH);

            // TODO: Check return value from MultiByteWideChar to ensure
            //         success.
 
            // Save the link by calling IPersistFile::Save.
            hres = ppf->Save(wsz, true);
            ppf->Release();
        }
        psl->Release();
    }
   
    return hres;
}

//int STDCALL
/*WinMain (HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmd, int nShow)
 {
  HRESULT hres;

  hres = CreateLink("C:\\Documents and Settings\\Savovski\\Desktop\\My Programming Files\\shortcut.cpp",
                    "shortcut.lnk",
                    "My own Shortcut made with MinGw C++" );

  return hres;
 }*/
